Implementing Unit Tests | unittest
The unittest is built into the standard Python library used for testing with Python. import unittest should be the starting line of code for using it. Depends upon the python version, it should differ as later versions of Python supports unittest and earlier versions supported unittest2.
Example:
In this example, a unit test class that checks if the sum of a list of numbers matches an expected value using the unittest framework in Python.
# import library
import unittest
# create a class
class TestXXXXX(unittest.TestCase):
# define a function
def test_xxxxxxx(self):
data = [100, 200, 300]
result = sum(data)
self.assertEqual(result, 6000)
# driver code
if __name__ == '__main__':
unittest.main()
Output:
======================================================================
.F
FAIL: test_xxxxxxx (__main__.TestXXXXX)
----------------------------------------------------------------------
Traceback (most recent call last):
File "......py", line 8, in test_xxxxxxx
self.assertEqual(result, 6000)
AssertionError: 600 != 6000
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
Getting Started With Unit Testing in Python
In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we will learn about Python Testing with the help of examples and proper explanations.
Table of Content
- What is Python Unit Testing?
- The Assert Statement
- Implementing Unit Tests | Unittest
- Implementing Unit Tests | Pytest
- Implementing Unit Tests | Nose
- Implementing Unit Tests | Doctest
- How to Write Assertions in Python Testing
- More Advanced Testing Scenarios
- Automating the Execution of Tests